import Layouts from '@/src/components/Layouts'
import React, { useEffect, useRef, useState } from 'react'
import { Card, Button, Table, Switch, Space, Image, Modal, Form, Input, message, Popconfirm, Drawer, Select } from 'antd';
import HousingSearch from '@/src/components/HousingSearch';
import http from '@/src/utils/https';
import Paginations from '@/src/components/Pagination';
import Link from 'next/link';

const index = () => {
  const [open, setOpen] = useState(false);
  const [jjrid, setjjrid] = useState({} as any);
  const [jjrval, setjjrval] = useState({} as any);
  let [istab, SetisTab] = useState(false)
  //请求初始数据
  let [housList, setHouslist] = useState([] as any)
  let [secsList, setSecslist] = useState([] as any)
  //渲染数据
  let [housLists, setHouslists] = useState([] as any)
  let [secsLists, setSecslists] = useState([] as any)
  //经纪人
  let [jjrlist, setjjrlist] = useState([] as any)


  //分页
  let [page, setPage] = useState(1);
  let [pagesize, SetpageSize] = useState(10);
  let [total, SetTotal] = useState(100);
  let [num1, Setnum1] = useState(1);
  let [num2, Setnum2] = useState(1);

  useEffect(() => {
    if (housList.length > 0 && istab) {
      let newList = housList.slice((page - 1) * pagesize, page * pagesize).map((item: any) => {
        item.key = item.id
        return item
      })
      setHouslists(newList)
      console.log(newList, "hous page")
    }
  }, [housList, page, pagesize])

  useEffect(() => {
    if (secsList.length > 0 && !istab) {
      let newList = secsList.slice((page - 1) * pagesize, page * pagesize).map((item: any) => {
        item.key = item.id
        return item
      })
      setSecslists(newList)
      // console.log(newList, "sec page")
    }

  }, [secsList, page, pagesize])
  //列表切换
  const handeltab = (num: number) => {
    if (num == 1) {
      SetisTab(false)
      SetTotal(num1)
    }
    if (num == 2) {
      SetisTab(true)
      SetTotal(num2)
    }
    setPage(1)
    SetpageSize(10)
  }
  //获取房源数据
  const gethousingList = async () => {
    // console.log(1111)
    let res = await http.get("/housing");
    // console.log(res.data.data, "hous res")
    if (res.data.code == 200) {
      Setnum1(res.data.data.length)
      setHouslist(res.data.data)
    }

  }
  //获取二手数据
  const getsechousingList = async () => {
    let res = await http.get("/second/housing");
    if (res.data.code == 200) {
      Setnum2(res.data.data.length)
      SetTotal(res.data.data.length)
      setSecslist(res.data.data)
    }
  }
  //获取经纪人
  const getjjr = async () => {
    let res = await http.get("/broker");
    if (res.data.code == 200) {
      //筛选在职经纪人
      let newList = res.data.data.filter((item:any)=>item.state == "在职")
      setjjrlist(newList)
      // console.log(res.data.data, "jjr")
    }
  }
  //抽屉 经纪人
  const showDrawer = (id: any) => {
    setOpen(true);
    setjjrid(id.id)
    setjjrval(id.jjr)
  };

  const onClose = () => {
    setOpen(false);
  };


  //请求数据
  useEffect(() => {
    if (secsList.length <= 0) {
      getsechousingList()
    }
    if (housList.length <= 0) {
      gethousingList()
    }
    if (jjrlist.length <= 0) {
      getjjr()
    }
  }, [])
  useEffect(() => {
    if (!istab) {
      getsechousingList()
    } else {
      gethousingList()
    }
  }, [istab])

  //表单回填
  //弹框
  const [form] = Form.useForm<{ username: string; address: string, price: string, city: string }>();
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [id, setid] = useState('')
  let [isedit, setedit] = useState(true)
  //编辑功能
  let [editlist, setEditlist] = useState({} as any)
  //点击弹开弹框，回填数据
  const handelshow = (obj: any) => {
    setEditlist(obj)
    showModal()
    setid(obj.id)
    form.setFieldValue("username", obj.name)
    form.setFieldValue("address", obj.xq)
    form.setFieldValue("price", obj.jiage)
    form.setFieldValue("city", obj.quyu)
  }
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);

  };


  //删除表单
  const handeldelete = async (id: any) => {
    if (!istab) {
      //sec
      let res = await http.delete("/deleteRenthouses", { params: { id } })
      console.log(res, "delete res sec")
      if (res.data.code == 200) {
        getsechousingList()
      }
      message.warning(res.data.message)
    } else {
      //hous
      let res = await http.delete("/deleteMarkethouses", { params: { id } })
      console.log(res, "delete res hous")
      if (res.data.code == 200) {
        gethousingList()
      }
      message.warning(res.data.message)
    }
  }
  //编辑表单

  const onFinish = async (values: any) => {
    console.log('Success:', values);
    let obj = {
      ...editlist,
      name: values.username,
      xq: values.address,
      quyu: values.city,
      jiage: values.price
    }
    delete obj.key
    console.log(values, id, "11111111111111111 id")

    let addobj = {
      name: values.username,
      xq: values.address,
      quyu: values.city,
      jiage: values.price
    }
    if (!istab) {
      //sec
      if (isedit) {
        console.log("编辑 sec")
        let res = await http.post("/second/edit", obj)
        if (res.data.code == 200) {
          getsechousingList()
        }
      }
      else {
        console.log('新增 sec')
        ///second/add
        let res = await http.post("/second/add", addobj)
        if (res.data.code == 200) {
          getsechousingList()
        }
      }
    } else {
      //hous
      if (isedit) {
        console.log("编辑 hous")
        let res = await http.post("/rent/edit", obj)
        if (res.data.code == 200) {
          gethousingList()
        }

      }
      else {
        console.log('新增 hous')
        let res = await http.post("/rent/add", addobj)
        console.log(321, res)
        if (res.status == 200) {
          console.log(123)
          gethousingList()
        }
      }
    }


    setIsModalOpen(false);
  };
  //新增
  const handeladd = () => {
    setedit(false)
    form.setFieldValue("username", '')
    form.setFieldValue("address", '')
    form.setFieldValue("price", '')
    form.setFieldValue("city", '')
    showModal()
  }
  const onFinishFailed = (errorInfo: any) => {
     //输入框为空时提示消息
     errorInfo.errorFields.map((item:any)=>{
      message.warning(item.errors)
    }) 
  };
  let columns = [
    {
      title: '楼盘名称',
      dataIndex: 'name',
      key: 'name',
      width: 160
    },
    {
      title: '详细地址',
      dataIndex: 'xq',
      key: 'xq',
      width: 100
    },
    {
      title: '价格',
      dataIndex: 'jiage',
      key: 'jiage',
      render: (_: any, record: any) => {

        return <div> {record.jiage} /元</div>
      },
      width: 99
    },
    {
      title: '排序',
      dataIndex: 'll',
      key: 'll',
      width: 70
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (_: any, record: any) => {

        return <div> {new Date(record.updated_at).toLocaleString()}</div>
      },
      width: 166
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (_: any, record: any) => {

        return <div> <Switch defaultChecked={false} /> </div>
      },
      width: 80
    },
    {
      title: '户型',
      dataIndex: 'jjr',
      key: 'jjr',
      render: (_: any, record: any) => {

        return <Image
          width={50}
          height={50}
          src={record.img}
          fallback="https://img2.baidu.com/it/u=3331916892,1334165774&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800"
        />
      },
      width: 90
    },
    {
      title: '操作',
      dataIndex: 'edit',
      key: 'edit',
      render: (_: any, record: any) => {
        let obj = JSON.stringify(record);
        return <div className='edit_btn'>
          <Space>
            <Button type="link">
              <Link href={{ pathname: "/detail/" + record.id, query: { obj } }} target="_blank"><span>详情</span></Link>
            </Button>
            <Button type="link"
              onClick={() => handelshow(record)}
            >编辑</Button>


            <Popconfirm
              title="删除这个"
              description="你确定要删除吗"
              onConfirm={() => handeldelete(record.id)}
              okText="Yes"
              cancelText="No"
            >
              <Button type="link"

              >删除</Button>
            </Popconfirm>
            <Button type="link"
              onClick={() => {
                message.warning("权限不够呢，小弟弟！！！")
              }}
            >经纪人</Button>
          </Space>
        </div>
      },
      width: 180
    },
  ] as any;

  let columns1 = [
    {
      title: '楼盘名称',
      dataIndex: 'name',
      key: 'name',
      width: 160
    },
    {
      title: '详细地址',
      dataIndex: 'xq',
      key: 'xq',
      width: 100
    },
    {
      title: '价格',
      dataIndex: 'jiage',
      key: 'jiage',
      render: (_: any, record: any) => {

        return <div> {record.jiage} /元</div>
      },
      width: 99
    },
    {
      title: '排序',
      dataIndex: 'll',
      key: 'll',
      width: 70
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (_: any, record: any) => {

        return <div> {new Date(record.updated_at).toLocaleString()}</div>
      },
      width: 166
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (_: any, record: any) => {

        return <div> <Switch defaultChecked={false} /> </div>
      },
      width: 80
    },
    {
      title: '户型',
      dataIndex: 'jjr',
      key: 'jjr',
      width: 90
    },
    {
      title: '操作',
      dataIndex: 'edit',
      key: 'edit',
      render: (_: any, record: any) => {
        let obj = JSON.stringify(record);
        return <div className='edit_btn'>
          <Space>
            <Button type="link">
              <Link href={{ pathname: "/detail/" + record.id, query: { obj } }} target="_blank"><span>详情</span></Link>
            </Button>
            <Button type="link"
              onClick={() => handelshow(record)}
            >编辑</Button>
            <Popconfirm
              title="删除这个"
              description="你确定要删除吗"
              onConfirm={() => handeldelete(record.id)}
              okText="Yes"
              cancelText="No"
            >
              <Button type="link"

              >删除</Button>
            </Popconfirm>
            <Button type="link"
              onClick={() => showDrawer(record)}
            >经纪人</Button>
          </Space>
        </div>
      },
      width: 180
    },
  ] as any;

  //经纪人
  const addjjr = async () => {
    console.log(jjrid,jjrval)
    if(istab){
      let res = await http.post('/alterRentBroker',{id:jjrid,jjr:jjrval})
      if(res.data.code==200){
        gethousingList()
        setOpen(false);
      }
    }
  }
  const handleChange = (value: string) => {
      setjjrval(value)
  };




  const handelpage = (page: number, pagesize: number) => {
    // console.log(page, pagesize, "page")
    setPage(page)
    SetpageSize(pagesize)
  }
  const handelsize = (page: number, pagesize: number) => {
    // console.log(page, pagesize, "size")
    setPage(page)
    SetpageSize(pagesize)
  }
  const tosearch = (obj: any) => {
    let name = obj.username;
    //模糊搜索
    if (name) {
      if (!istab) {
        ///sec  
        let res = secsList.filter((item: any) => item.name.includes(name))
        console.log(res, "sec search")
        setSecslist([...res])
        setPage(1)
        SetpageSize(10),
          SetTotal(res.length)
      } else {
        //hous
        let res = housList.filter((item: any) => item.name.includes(name))
        console.log(res, "hous search")
        setHouslist([...res])
        setPage(1)
        SetpageSize(10),
          SetTotal(res.length)
      }
    } else {
      location.reload()
    }
  }


  return (
    <Layouts>
      <Card bordered={false} title="房源管理" style={{ width: '100%' }} >
        <Space>
          <Button type={istab ? "default" : "primary"} onClick={() => handeltab(1)}>销售楼盘</Button>
          <Button type={istab ? "primary" : "default"} onClick={() => handeltab(2)}>房屋租聘</Button>
        </Space>
      </Card>
      <Card style={{ width: '100%',minWidth:"1300px" }} bordered={false}>

        <HousingSearch handelsearch={tosearch}></HousingSearch>


      </Card>"
      <Card style={{ width: '100%', height: "600px", padding: "12px 12px 80px 12px" }} extra={<Button type="primary"
        onClick={handeladd}
      >新增</Button>}>
        {
          !istab ? <Table scroll={{ y: 480 }} style={{ height: 480 }} pagination={false} columns={columns} dataSource={secsLists}> </Table>
            : <Table scroll={{ y: 480 }} style={{ height: 480 }} pagination={false} columns={columns1} dataSource={housLists}> </Table>
        }
      </Card>
      <Card bordered={false} style={{ width: '100%', position: "sticky", left: "0", bottom: "0", zIndex: "9",minWidth:"800px"}}>
        <Paginations
          total={total}
          page={page}
          pagesize={pagesize}
          onpage={handelpage}
          onsize={handelsize}
        ></Paginations>
      </Card>


      <Modal title="编辑" open={isModalOpen} footer={false} onCancel={handleCancel}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"

        >
          <Form.Item
            label="楼盘名称"
            name="username"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="详细地址"
            name="address"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="价格"
            name="price"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="区域"
            name="city"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button type="default" onClick={handleCancel}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
      <Drawer title="经纪人" placement="right" onClose={onClose} open={open}>

        <Card style={{ width: '100%' }} bordered={false}>

          <Select
            value={jjrval}
            style={{ width: 120 }}
            onChange={handleChange}
            options={jjrlist.map((item:any)=>{
              return {
                value:item.name,
                label:item.name,
                key:item.id
              }
            })}
          />

        </Card>
        <Card style={{ width: '100%' }} bordered={false}>
          <Button type="link"
            onClick={addjjr}
          >确定</Button>
        </Card>
      </Drawer>
    </Layouts>
  )
}

export default index